package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UsrMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.management.snmp.util.SnmpLoadedClassData;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UsrMapper usrMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间内的营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
//            日期计算，如果不到end，逐步加一
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
//        存放每天的营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate date : dateList) {
//            查询每天的营业额，然后添加到List集合中
            final LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            final LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumByMap(map);
//            对返回值做一下非空处理
            turnover=turnover==null?0:turnover;
            turnoverList.add(turnover);
        }

//        按要求封装返回的数据集
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     *统计指定时间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
//        存放从begin到end之间的每天日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
//            日期计算，如果不到end，逐步加一
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> totalUserList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();
//        遍历dateList集合，查询每天的新用户和总用户数量
        for (LocalDate date : dateList) {
            final LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            final LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            Integer totalusercount=usrMapper.countByMap(map);
            totalUserList.add(totalusercount);
            map.put("begin",beginTime);
            Integer newusercount=usrMapper.countByMap(map);
            newUserList.add(newusercount);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     *统计指定时间内的订单信息
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //        存放从begin到end之间的每天日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
//            日期计算，如果不到end，逐步加一
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        Integer totalOrderCount=0;
        Integer validOrderCount=0;
//        遍历dateList集合，查询每天的新用户和总用户数量
        for (LocalDate date : dateList) {
            final LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            final LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
//         查询每天的订单总数
            Integer orderSum=orderMapper.orderSumByMap(map);
            totalOrderCount+=orderSum;
            orderCountList.add(orderSum);
//         查询每天的有效订单数
            map.put("status", Orders.COMPLETED);
            Integer completeorder=orderMapper.orderSumByMap(map);
            validOrderCount+=completeorder;
            validOrderCountList.add(completeorder);
        }
//            教程写法
            Integer totalorderCount=orderCountList.stream().reduce(Integer::sum).get();
            Integer validorderCount = validOrderCountList.stream().reduce(Integer::sum).get();
            Double ordercompletionRate=0.0;
            if (totalorderCount!=0){
                ordercompletionRate=validorderCount.doubleValue()/totalorderCount;
            }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
//                .totalOrderCount(totalOrderCount)
                .totalOrderCount(totalorderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
//                .validOrderCount(validOrderCount)
                .validOrderCount(validorderCount)
//                .orderCompletionRate((validOrderCount.doubleValue()/totalOrderCount))
                .orderCompletionRate(ordercompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
       LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
       LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10=orderMapper.getSalesTop10(begintime,endtime);
        List<String> names=salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        final String nameList = StringUtils.join(names, ",");

        List<Integer> numbers=salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        final String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
//1.查询数据库，获取营业额数据（最近30天）
        LocalDate dateBegin=LocalDate.now().minusDays(31);
        LocalDate dateEnd=LocalDate.now().minusDays(1);
//        查询概览数据
        BusinessDataVO businessDataVO=workspaceService.getBusinessData(LocalDateTime.of(dateBegin,LocalTime.MIN),LocalDateTime.of(dateEnd,LocalTime.MAX));
//        2.通过poi写入daoexcel文件中
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
//            获取表格对象
            XSSFWorkbook excel=new XSSFWorkbook(in);
            XSSFSheet sheet=excel.getSheet("Sheet1");
//             写入时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
//            第四行
            XSSFRow row=sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
//            操作第五航
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
//            填充下部 明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date=dateBegin.plusDays(1);
//                查询某一天的营业数据
                BusinessDataVO busOneday=workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
//                获得某一行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

//                通过输出流把excel文件数据写入并下载到客户端浏览器
                ServletOutputStream out=response.getOutputStream();
                excel.write(out);

//                关闭资源
                out.close();
                excel.close();
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
